package com.cabinet.web.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.cabinet.service.AdminServiceImpl;
import cn.com.easy.utils.CookieUtils;
import cn.com.easy.utils.SecurityUtils;

@Controller
@RequestMapping()
public class LonginController {
	@Autowired
	private AdminServiceImpl adminServiceImpl;
	
	@RequestMapping()
	public String login(HttpServletRequest request,ModelMap modelMap) throws Exception{
		String adminCount = CookieUtils.getCookieValue(request, "adminCount");
		System.out.println("loginCheck:"+adminCount);
		if(adminCount == "null" || adminCount == null){
			return "/login/admin_login";
		}else{
			modelMap.addAttribute("adminCount", adminCount);
			return "/index/index";
		}
		
	}

	@RequestMapping("/loginCheck")
	public String loginCheck(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap,String account , String password) throws Exception{
		String adminCount = CookieUtils.getCookieValue(request, "adminCount");
		System.out.println("loginCheck:"+adminCount);
		if(adminCount == "null" || adminCount == null){
			if(adminServiceImpl.checkManger(account, SecurityUtils.SHA256(password))){
				//设置cookie
				CookieUtils.setCookie(request, response, "adminCount",account);
				//System.out.println(CookieUtils.getCookieRedirectUrl(request));		
					modelMap.addAttribute("adminCount", account);
					return "/index/index";
			}else{
				//System.out.println("false");
				modelMap.addAttribute("loginMessage", "账号不存在或密码不正确！");
				return "/login/admin_login";
			}
		}else{
			return "redirect:"+CookieUtils.getCookieRedirectUrl(request);
		}
	
		
	}
	
	@RequestMapping("/loginOut")
	public String loginOut(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Cookie cookie = CookieUtils.getCookie(request, "adminCount");
		CookieUtils.deleteCookie(request, response, cookie);
		return "redirect:/";
	}
}
